import click
from datetime import datetime
from flask import current_app
from app.utils.wx_token_manager import token_manager


def register_commands(app):
    @app.cli.group()
    def wechat():
        """微信相关命令"""
        pass

    @wechat.command()
    def get_token():
        """获取当前的access_token"""
        token = token_manager.get_access_token()
        if token:
            masked_token = token[:10] + "..." + token[-4:] if len(token) > 14 else "***"
            click.echo(f"当前access_token: {masked_token}")

            # 显示token信息
            status = token_manager.get_config_status()
            if status["token_expires_at"]:
                expires_at = status["token_expires_at"]
                remaining = (expires_at - datetime.now()).total_seconds() / 60
                click.echo(f"过期时间: {expires_at.strftime('%Y-%m-%d %H:%M:%S')}")
                click.echo(f"剩余时间: {remaining:.1f}分钟")
        else:
            click.echo("获取access_token失败")

    @wechat.command()
    def refresh_token():
        """强制刷新access_token"""
        token = token_manager.get_access_token(force_refresh=True)
        if token:
            masked_token = token[:10] + "..." + token[-4:] if len(token) > 14 else "***"
            click.echo(f"刷新后的access_token: {masked_token}")

            # 显示token信息
            status = token_manager.get_config_status()
            if status["token_expires_at"]:
                expires_at = status["token_expires_at"]
                remaining = (expires_at - datetime.now()).total_seconds() / 60
                click.echo(f"过期时间: {expires_at.strftime('%Y-%m-%d %H:%M:%S')}")
                click.echo(f"剩余时间: {remaining:.1f}分钟")
        else:
            click.echo("刷新access_token失败")

    @wechat.command()
    def config():
        """显示当前的微信配置信息"""
        status = token_manager.get_config_status()

        click.echo("微信小程序配置信息:")
        click.echo(f"AppID: {status['appid']}")
        click.echo(f"AppSecret: {'已设置' if status['has_secret'] else '未设置'}")
        click.echo(f"Token文件: {status['token_file']}")

        if status["has_token"]:
            click.echo(f"Token状态: 已获取")
            if status["token_expires_at"]:
                expires_at = status["token_expires_at"]
                remaining = (expires_at - datetime.now()).total_seconds() / 60
                click.echo(f"过期时间: {expires_at.strftime('%Y-%m-%d %H:%M:%S')}")
                click.echo(f"剩余时间: {remaining:.1f}分钟")
        else:
            click.echo("Token状态: 未获取")
